package teach.shuji.java12.system.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import teach.shuji.java12.system.dto.LoginModel;
import teach.shuji.java12.system.dto.LoginResult;
import teach.shuji.java12.system.entity.User;
import teach.shuji.java12.system.enums.LoginStatus;
import teach.shuji.java12.system.mapper.UserMapper;
import teach.shuji.java12.system.service.AccountService;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    UserMapper userMapper;

    @Override
    public LoginResult login(LoginModel model) {
        LoginResult result = new LoginResult();

        //用以下代码取代sql语句
        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<User>();
        //lambda查询 查询User表
        userQuery.eq(User::getUserName, model.getAccount());
        // user字段 equals(==)  model里的用户名
        // 相当于sql: select * from user where username='从model传来的用户名'

        // mp优点：和sql无关，方便转换数据库
        // 缺点：性能上差一点点，可以忽略
        //      看起来没有sql直观
        // 我给XX单位做了X个软件  mysql
        // 单位要求：使用国产数据库 kingbase 换掉 mysql
        // mysql: select * from ..... limit 1
        // kingbase : select top 1 * from .....

        User u = userMapper.selectOne(userQuery);

        if(u == null) {
            //用户不存在
            result.setStatus(LoginStatus.UserNotExsits);
            return result;
        }
        if(u.getDelFlag()=='1') {
            //用户不存在
            result.setStatus(LoginStatus.UserNotExsits);
            return result;
        }
        if(u.getStatus()=='1'){
            // 用户被禁用
            result.setStatus(LoginStatus.UserNotActive);
            return result;
        }


        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String digestHex = md5.digestHex(model.getPassword() + u.getSalt());
        System.out.println(digestHex);

        if(!u.getPassword().equals(digestHex)){
            result.setStatus(LoginStatus.PasswordError);
            return result;
        }

        // sa-token 记录登录信息
        StpUtil.login(u.getId());

        // 记录 最后登录IP 和 时间
        u.setLoginIp(model.getIp());
        u.setLoginDate(DateTime.now().toLocalDateTime());

        userMapper.updateById(u);

        result.setStatus(LoginStatus.Success);
        result.setToken(StpUtil.getTokenValue());
        return result;
    }
}
